// 导入路由相关方法
import {
    createRouter,
    createWebHistory,
    createWebHashHistory,
    createMemoryHistory
} from 'vue-router'
// 导入所需的各个组件
import StudentInfo from '@/components/StudentInfo.vue'
import Login from '@/components/Login.vue'
import Counter from '@/components/Counter.vue'
import Work from '@/components/Work.vue'
import MoYu from '@/components/MoYu.vue'
import Coding from '@/components/Coding.vue'
import Debuging from '@/components/Debuging.vue'
import { useTokenStore } from '@/store/tokenStore'

// 定义各路由路径、路由名称、显示的视图组件
const routes = [
    {
        path: '/',
        name: 'root',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/register',
        name: 'register',
        component: MoYu
    },
    {
        path: '/student-infos',
        name: 'Student Infos',
        component: StudentInfo
    },
    {
        path: '/work',
        component: Work,
        children: [
            {
                path: 'coding',
                component: Coding
            },
            {
                path: 'debuging',
                component: Debuging
            }
        ]
    }
    // { path: '/:pathMatch(.*)', component: Login }
]
// createRouter为路由创建的主方法
const router = createRouter({
    history: createWebHistory(), // createWebHistory为创建历史模式的路由实例
    routes
})

router.onError((err) => {
    console.log(err)
    console.log('error occur')
})

router.beforeEach((to, from) => {
    const tokenStore = useTokenStore()
    if (tokenStore.token == '' && to.path != '/login') {
        return '/login'
    }
    return true
    // console.log(undefinedVariable)
    // if (to.path != '/login') {
    //     return '/login'
    // }
})

export default router
